//
//  ScanViewController.m
//  阿帕
//
//  Created 阿帕 on 2020/4/22.
//  Copyright © 2020 GCY. All rights reserved.
//

#import "ScanViewController.h"
#import "LBXScanVideoZoomView.h"
#import "LBXPermission.h"
#import "LBXPermissionSetting.h"
#import "LBXAlertAction.h"
#import "QRZhuangHuoViewController.h"
#import "YunDanCenterTabbar.h"
#import "DriverVehicleModel.h"
#import "HuoYuanDetailViewController.h"
#import "YunDanCenterDetailViewController.h"
#import "ZTXProjectListCodeController.h"

typedef void(^VehileCodeBlock)(NSString *vehicleCode, NSArray *vehicleArr);

@interface ScanViewController ()

@property (nonatomic, strong) LBXScanVideoZoomView *zoomView;

@end

@implementation ScanViewController

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
    [self drawBottomItems];
    [self drawTitle];
    [self.view bringSubviewToFront:_topTitle];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    if ([self respondsToSelector:@selector(setEdgesForExtendedLayout:)]) {
        
        self.edgesForExtendedLayout = UIRectEdgeNone;
    }
    if (_pageFlag == 1) {
        self.navigationItem.title = @"扫码装卸货";
    } else {
        self.navigationItem.title = @"扫码绑车";
    }
    
    self.cameraInvokeMsg = @"相机启动中";
    
    //设置扫码后需要扫码图像
    self.isNeedScanImage = YES;
}
//绘制扫描区域
- (void)drawTitle
{
    if (!_topTitle)
    {
        self.topTitle = [[UILabel alloc]init];
        _topTitle.bounds = CGRectMake(0, 0, 145, 60);
        _topTitle.center = CGPointMake(CGRectGetWidth(self.view.frame)/2, 50);
        
        //3.5inch iphone
        if ([UIScreen mainScreen].bounds.size.height <= 568 )
        {
            _topTitle.center = CGPointMake(CGRectGetWidth(self.view.frame)/2, 38);
            _topTitle.font = [UIFont systemFontOfSize:14];
        }
        
        _topTitle.textAlignment = NSTextAlignmentCenter;
        _topTitle.numberOfLines = 0;
        _topTitle.text = @"将取景框对准二维码即可自动扫描";
        _topTitle.textColor = [UIColor whiteColor];
        [self.view addSubview:_topTitle];
    }
}

- (void)cameraInitOver
{
    if (self.isVideoZoom) {
        [self zoomView];
    }
}

- (LBXScanVideoZoomView*)zoomView
{
    if (!_zoomView)
    {
        
        CGRect frame = self.view.frame;
        
        int XRetangleLeft = self.style.xScanRetangleOffset;
        
        CGSize sizeRetangle = CGSizeMake(frame.size.width - XRetangleLeft*2, frame.size.width - XRetangleLeft*2);
        
        if (self.style.whRatio != 1)
        {
            CGFloat w = sizeRetangle.width;
            CGFloat h = w / self.style.whRatio;
            
            NSInteger hInt = (NSInteger)h;
            h  = hInt;
            
            sizeRetangle = CGSizeMake(w, h);
        }
        
        CGFloat videoMaxScale = [self.scanObj getVideoMaxScale];
        
        //扫码区域Y轴最小坐标
        CGFloat YMinRetangle = frame.size.height / 2.0 - sizeRetangle.height/2.0 - self.style.centerUpOffset;
        CGFloat YMaxRetangle = YMinRetangle + sizeRetangle.height;
        
        CGFloat zoomw = sizeRetangle.width + 40;
        _zoomView = [[LBXScanVideoZoomView alloc]initWithFrame:CGRectMake((CGRectGetWidth(self.view.frame)-zoomw)/2, YMaxRetangle + 40, zoomw, 18)];
        
        [_zoomView setMaximunValue:videoMaxScale/4];
        
        
        __weak __typeof(self) weakSelf = self;
        _zoomView.block= ^(float value)
        {
            [weakSelf.scanObj setVideoScale:value];
        };
        [self.view addSubview:_zoomView];
        
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tap)];
        [self.view addGestureRecognizer:tap];
    }
    
    return _zoomView;
    
}

- (void)tap
{
    _zoomView.hidden = !_zoomView.hidden;
}

- (void)drawBottomItems
{
    if (_bottomItemsView) {
        
        return;
    }
    
    self.bottomItemsView = [[UIView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(self.view.frame)-164,
                                                                   CGRectGetWidth(self.view.frame), 100)];
    _bottomItemsView.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.6];
    
    [self.view addSubview:_bottomItemsView];
    
    CGSize size = CGSizeMake(65, 87);
    self.btnFlash = [[UIButton alloc]init];
    _btnFlash.bounds = CGRectMake(0, 0, size.width, size.height);
    _btnFlash.center = CGPointMake(CGRectGetWidth(_bottomItemsView.frame)/3, CGRectGetHeight(_bottomItemsView.frame)/2);
    [_btnFlash setImage:[UIImage imageNamed:@"CodeScan.bundle/qrcode_scan_btn_flash_nor"] forState:UIControlStateNormal];
    [_btnFlash addTarget:self action:@selector(openOrCloseFlash) forControlEvents:UIControlEventTouchUpInside];
    
    self.btnPhoto = [[UIButton alloc]init];
    _btnPhoto.bounds = _btnFlash.bounds;
    _btnPhoto.center = CGPointMake(CGRectGetWidth(_bottomItemsView.frame)/1.5, CGRectGetHeight(_bottomItemsView.frame)/2);
    [_btnPhoto setImage:[UIImage imageNamed:@"CodeScan.bundle/qrcode_scan_btn_photo_nor"] forState:UIControlStateNormal];
    [_btnPhoto setImage:[UIImage imageNamed:@"CodeScan.bundle/qrcode_scan_btn_photo_down"] forState:UIControlStateHighlighted];
    [_btnPhoto addTarget:self action:@selector(openPhoto) forControlEvents:UIControlEventTouchUpInside];
    
    
    [_bottomItemsView addSubview:_btnFlash];
    [_bottomItemsView addSubview:_btnPhoto];
    
}
#pragma mark -实现类继承该方法，作出对应处理

- (void)scanResultWithArray:(NSArray<LBXScanResult*>*)array
{
    if (!array ||  array.count < 1)
    {
        [self popAlertMsgWithScanResult:nil];
        
        return;
    }
    
    //    经测试，可以ZXing同时识别2个二维码，不能同时识别二维码和条形码
    for (LBXScanResult *result in array) {
        
        NSLog(@"scanResult:%@",result.strScanned);
    }
    
    LBXScanResult *scanResult = array[0];
    
    NSString*strResult = scanResult.strScanned;
    
    self.scanImage = scanResult.imgScanned;
    
    if (!strResult) {
        
        [self popAlertMsgWithScanResult:nil];
        
        return;
    }
    
    [self showNextVCWithScanResult:scanResult];
}

- (void)popAlertMsgWithScanResult:(NSString*)strResult
{
    if (!strResult) {
        
        strResult = @"识别失败";
    }
    
    __weak __typeof(self) weakSelf = self;
    [LBXAlertAction showAlertWithTitle:@"扫码内容" msg:strResult buttonsStatement:@[@"知道了"] chooseBlock:^(NSInteger buttonIdx) {
        
        [weakSelf reStartDevice];
    }];
}
//获取链接中各个参数值
- (NSDictionary *)getParamsWithUrlString:(NSString *)urlString
{
    if (urlString.length == 0) {
        NSLog(@"链接为空！");
        return @{};
    }
    //先截取问号
    NSArray * allElements = [urlString componentsSeparatedByString:@"?"];
    NSMutableDictionary * params = [NSMutableDictionary dictionary];
    if (allElements.count == 2) {
        //有参数或者？后面为空
        NSString * paramString = allElements[1];
        //获取参数对
        NSArray * paramsArray = [paramString componentsSeparatedByString:@"&"];
        if (paramsArray.count >= 2) {
            for (NSInteger i = 0; i<paramsArray.count; i++) {
                NSString * singleParamString = paramsArray[i];
                NSArray * singleParamSet = [singleParamString componentsSeparatedByString:@"="];
                if (singleParamSet.count == 2) {
                    NSString * key = singleParamSet[0];
                    NSString * value = singleParamSet[1];
                    if (key.length > 0 || value.length > 0) {
                        [params setObject:value.length > 0 ? value:@"" forKey:key.length > 0 ? key:@""];
                    }
                }
            }
        }else if (paramsArray.count == 1){ //无& url只有？后一个参数
            NSString * singleParamString = paramsArray[0];
            NSArray * singleParamSet = [singleParamString componentsSeparatedByString:@"="];
            if (singleParamSet.count == 2) {
                NSString * key = singleParamSet[0];
                NSString * value = singleParamSet[1];
                if (key.length > 0 || value.length > 0) {
                    [params setObject:value.length > 0 ? value:@"" forKey:key.length > 0 ? key:@""];
                }
            }else{
                //问号后面什么都没有 xxxx？ 无需处理
            }
        }
        //整合url及参数
        return [params copy];
    }else if (allElements.count > 2){
        NSLog(@"链接不合法！链接包含多个？");
        return @{};
    }else{
        NSLog(@"链接不包含参数!");
        return @{};
    }
}
- (void)showNextVCWithScanResult:(LBXScanResult*)strResult {
    WEAKSELF
    DebugLog(@"二维码为：%@",strResult.strScanned);
    NSDictionary * dic = [self getParamsWithUrlString:strResult.strScanned];
    
//    NSDictionary *dic = [DCSpeedy dictionaryWithJsonString:strResult.strScanned];
    dic = DictionaryCheck(dic);
    
    DebugLog(@"dic为：%@",dic);
    
    if (_pageFlag == 1) {
        
        // 2k扫码接单
        if ([dic[@"type"] isEqualToString:@"teamLoadingQrCode"]) {
            // 2k车队司机/加入车队的独立司机--扫码接单（接车队长接过的单子）
            
            [self getVehicleCode:^(NSString *vehicleCode, NSArray *vehicleArr) {
                
                YunDanCenterDetailViewController *yddVC = [YunDanCenterDetailViewController new];
                yddVC.orderCode = dic[@"code"];
                yddVC.takeOrderType = 2;
                yddVC.vehicleArr = vehicleArr;
                [weakSelf.navigationController pushViewController:yddVC animated:YES];
                
            } isShow:NO];

//            [self getVehicleCode:^(NSString *vehicleCode, NSArray *vehicleArr) {
//
//                NSString *url = CJStringWithFormat(@"%@%@",[NSString stringWithFormat:@"%@/ntocc-tms-api",[ReAddressDynamic shared].baseUrl], @"/teamOrder/receive");
//                NSDictionary *dicTemp = @{
//                    @"vehicleCode" : vehicleCode,
//                    @"code": StringCheck(dic[@"code"])
//                };
//                @weakify(self);
//                [HTTPManager postNetworkRequest:url
//                                  withParameter:dicTemp
//                                         withVC:self
//                                        netName:@"司机扫码车队长接单的二维码后自动接单"
//                                        success:^(id response, NSString *msg) {
//                    @strongify(self);
//                    YunDanCenterTabbar *vc = [YunDanCenterTabbar new];
//                    vc.selectedIndex = 2;
//                    [self.navigationController pushViewController:vc animated:YES];
//
//                } failure:^(NSInteger code, NSString *msg) {
//                    @strongify(self);
//                    [DCSpeedy dc_SetUpSingleAlterWithView:self Title:@"温馨提示" Message:msg tureTitle:@"确定" Sure:^{
//                        [self.navigationController popViewControllerAnimated:YES];
//                    }];
//                }];
//
//            } isShow:YES];
            
            // 2k车队长--扫码接单
        } else if ([StringCheck(dic[@"type"]) isEqual:@"orderDetailSingleQrCode"]) {
            
            YunDanCenterDetailViewController *yddVC = [YunDanCenterDetailViewController new];
            yddVC.orderCode = dic[@"code"];
            [weakSelf.navigationController pushViewController:yddVC animated:YES];
            
//            NSString *url = CJStringWithFormat(@"%@%@",[NSString stringWithFormat:@"%@/ntocc-tms-api",[ReAddressDynamic shared].baseUrl], @"/orderDetailSingle/singleOrderDetail");
//            NSDictionary *dicTemp = @{
//                @"code": StringCheck(dic[@"code"]),
//                @"driverCode":StringCheck([UserDefaultUtil valueForKey:UserPartyCode])};
//            @weakify(self);
//            [HTTPManager postNetworkRequest:url
//                              withParameter:dicTemp
//                                     withVC:self
//                                    netName:@"司机扫码车队长接单的二维码后自动接单"
//                                    success:^(id response, NSString *msg) {
//                @strongify(self);
//                YunDanCenterTabbar *vc = [YunDanCenterTabbar new];
//                vc.selectedIndex = 2;
//                [self.navigationController pushViewController:vc animated:YES];
//            } failure:^(NSInteger code, NSString *msg) {
//                @strongify(self);
//                [DCSpeedy dc_SetUpSingleAlterWithView:self Title:@"温馨提示" Message:msg tureTitle:@"确定" Sure:^{
//                    [self.navigationController popViewControllerAnimated:YES];
//                }];
//            }];
            
        } else if([dic[@"type"] isEqualToString:@"11"]){
            // 直接跳转货源详情
            HuoYuanDetailViewController *hydVC = [HuoYuanDetailViewController new];
            hydVC.orderCode = dic[@"code"];
            hydVC.type = @"1";
            [weakSelf.navigationController pushViewController:hydVC animated:YES];
        }else if([dic[@"type"] isEqualToString:@"12"]){
            //跳转项目单列表
            ZTXProjectListCodeController *hydVC = [ZTXProjectListCodeController new];
            hydVC.projectCode = dic[@"code"];
            [weakSelf.navigationController pushViewController:hydVC animated:YES];
        }else if([dic[@"type"] isEqualToString:@"2"]){
            [DCSpeedy dc_SetUpAlterWithView:self Title:@"温馨提示" Message:@"是否确认接单" Sure:^{
                NSMutableDictionary *pam = [NSMutableDictionary dictionary];
                [pam setValue:dic[@"tempCode"] forKey:@"tempCode"];
                [pam setValue:dic[@"mainOrderCode"] forKey:@"mainOrderCode"];
                [HTTPManager postNetworkRequest:CJStringWithFormat(@"%@/orderDetail/new/teamDriverReceiveOrderDetail",[NSString stringWithFormat:@"%@/ntocc-tms-api",[ReAddressDynamic shared].baseUrl]) withParameter:pam withVC:self netName:@"车队司机扫码接单" success:^(id response, NSString *msg) {
                    [XSInfoView showInfo:msg onView:self.view];
                    __weak __typeof(self)weakSelf = self;
                  weakSelf.navigationController.tabBarController.selectedIndex = 0;
                  [weakSelf.navigationController popToRootViewControllerAnimated:NO];
                    [KNotificationCenter postNotificationName:@"popToHomePushJieDan" object:nil];
                } failure:^(NSInteger code, NSString *msg) {
                    [DCSpeedy dc_SetUpSingleAlterWithView:self Title:@"温馨提示" Message:msg tureTitle:@"确定" Sure:^{
                        [weakSelf.navigationController popToRootViewControllerAnimated:YES];
                    }];
                }];
              
            } Cancel:^{
                [weakSelf.navigationController popToRootViewControllerAnimated:YES];
            }];
        }else if ([StringCheck(dic[@"type"]) isEqual:@"OwnersQRCode"]) {
            if([[UserDefaultUtil valueForKey:DRIVER_TYPE] integerValue] == 1){
                [DCSpeedy dc_SetUpSingleAlterWithView:self Title:@"温馨提示" Message:@"车队长不能绑定货主" tureTitle:@"确定" Sure:^{
                    [weakSelf.navigationController popToRootViewControllerAnimated:YES];
                }];
            }else{
                [DCSpeedy dc_SetUpAlterWithView:self Title:@"温馨提示" Message:@"是否绑定该货主" Sure:^{
                    NSMutableDictionary *pam = [NSMutableDictionary dictionary];
                    [pam setValue:StringCheck([UserDefaultUtil valueForKey:USER_CODE]) forKey:@"driverCode"];
                    [pam setValue:dic[@"code"] forKey:@"shipmentCode"];
                    [HTTPManager postNetworkRequest:CJStringWithFormat(@"%@/driver/bindShipmentByPartyCode",[NSString stringWithFormat:@"%@/ntocc-basic-api",[ReAddressDynamic shared].baseUrl]) withParameter:pam withVC:self netName:@"绑定货主" success:^(id response, NSString *msg) {
    //                    [XSInfoView showInfo:msg onView:self.view];
                        __weak __typeof(self)weakSelf = self;
                        if([response[@"authStatus"] intValue] == 0 || [response[@"authStatus"] intValue] == 2){
                            weakSelf.navigationController.tabBarController.selectedIndex = 1;
                            [weakSelf.navigationController popToRootViewControllerAnimated:NO];
                            [KNotificationCenter postNotificationName:@"popToHomePushRenZ" object:nil];
                        }else{
                            [DCSpeedy dc_SetUpSingleAlterWithView:self Title:@"温馨提示" Message:msg tureTitle:@"确定" Sure:^{
                                [weakSelf.navigationController popToRootViewControllerAnimated:YES];
                            }];
                        }
                    } failure:^(NSInteger code, NSString *msg) {
                        [DCSpeedy dc_SetUpSingleAlterWithView:self Title:@"温馨提示" Message:msg tureTitle:@"确定" Sure:^{
                            [weakSelf.navigationController popToRootViewControllerAnimated:YES];
                        }];
                    }];
                  
                } Cancel:^{
                    [weakSelf.navigationController popToRootViewControllerAnimated:YES];
                }];
            }
        }else{
            
            // 标准版扫码接单逻辑
            [HTTPManager getNetworkRequest:CJStringWithFormat(@"%@%@/%@",[NSString stringWithFormat:@"%@/ntocc-tms-api",[ReAddressDynamic shared].baseUrl], ORDER, dic[@"code"]) withParameter:@{@"token":[UserDefaultUtil valueForKey:USER_TOKEN],} withVC:self netName:@"货源详情信息" success:^(id response, NSString *msg) {
                
                NSDictionary *parentDic = response;
                NSMutableDictionary *pam = @{
                    @"mainOrderCode": dic[@"code"]
                    ,@"token":[UserDefaultUtil valueForKey:USER_TOKEN]
                }.mutableCopy;
                
                if ([dic[@"type"] isEqual:@"loadingQrCode"]) {
                    
                    // 直接跳转货源详情
//                    HuoYuanDetailViewController *hydVC = [HuoYuanDetailViewController new];
//                    hydVC.orderCode = dic[@"code"];
//                    [weakSelf.navigationController pushViewController:hydVC animated:YES];
                    
                    if (Identity_CarCaptain) { // 扫码接单--车队长

                        [self getVehicleCode:^(NSString *vehicleCode, NSArray *vehicleArr) {
                            [pam setValue:vehicleCode forKey:@"vehicleCode"];

                            [HTTPManager putNetworkRequest:CJStringWithFormat(@"%@%@",[NSString stringWithFormat:@"%@/ntocc-tms-api",[ReAddressDynamic shared].baseUrl], ORDERDETAIL_TAKEORDERANDLOADVERIFY)
                                             withParameter:pam
                                                    withVC:self
                                                   netName:@"扫码接单装货验证"
                                                   success:^(id response, NSString *msg) {

                                QRZhuangHuoViewController *qrzhvc = [[QRZhuangHuoViewController alloc] init];
                                qrzhvc.ydModel = [YunDanCenterModel mj_objectWithKeyValues:parentDic];
                                qrzhvc.startCountrySubdivisionCode = parentDic[@"shipperSubdivisionCode"];
                                qrzhvc.endCountrySubdivisionCode = parentDic[@"consigneeSubdivisionCode"];
                                qrzhvc.coalUnit = parentDic[@"coalUnit"];
                                qrzhvc.orderCode = parentDic[@"code"];
                                qrzhvc.code = dic[@"code"];
                                qrzhvc.branchCode = parentDic[@"branchCode"];
                                qrzhvc.shippingNoteNumber = @"";///装货时，在装货成功后才会返回这个字段
                                qrzhvc.status = 0;///装货
                                qrzhvc.vehicleCode = vehicleCode;
                                [weakSelf.navigationController pushViewController:qrzhvc animated:YES];

                            } failure:^(NSInteger code, NSString *msg) {

                                [DCSpeedy dc_SetUpSingleAlterWithView:self Title:@"温馨提示" Message:msg tureTitle:@"确定" Sure:^{
                                    [weakSelf.navigationController popViewControllerAnimated:YES];
                                }];

                            }];

                        } isShow:YES];

                    } else { // 扫码接单--司机

                        [HTTPManager putNetworkRequest:CJStringWithFormat(@"%@%@",[NSString stringWithFormat:@"%@/ntocc-tms-api",[ReAddressDynamic shared].baseUrl], ORDERDETAIL_TAKEORDERANDLOADVERIFY)
                                         withParameter:pam
                                                withVC:self
                                               netName:@"扫码接单装货验证"
                                               success:^(id response, NSString *msg) {

                            QRZhuangHuoViewController *qrzhvc = [[QRZhuangHuoViewController alloc] init];
                            qrzhvc.ydModel = [YunDanCenterModel mj_objectWithKeyValues:parentDic];
                            qrzhvc.startCountrySubdivisionCode = parentDic[@"shipperSubdivisionCode"];
                            qrzhvc.endCountrySubdivisionCode = parentDic[@"consigneeSubdivisionCode"];
                            qrzhvc.coalUnit = parentDic[@"coalUnit"];
                            qrzhvc.orderCode = parentDic[@"code"];
                            qrzhvc.code = dic[@"code"];
                            qrzhvc.branchCode = parentDic[@"branchCode"];
                            qrzhvc.shippingNoteNumber = @"";///装货时，在装货成功后才会返回这个字段
                            qrzhvc.status = 0;///装货
                            [weakSelf.navigationController pushViewController:qrzhvc animated:YES];

                        } failure:^(NSInteger code, NSString *msg) {

                            [DCSpeedy dc_SetUpSingleAlterWithView:self Title:@"温馨提示" Message:msg tureTitle:@"确定" Sure:^{
                                [weakSelf.navigationController popViewControllerAnimated:YES];
                            }];

                        }];
                    }
                    
                } else {
                    
                    [HTTPManager getNetworkRequest:CJStringWithFormat(@"%@%@",[NSString stringWithFormat:@"%@/ntocc-tms-api",[ReAddressDynamic shared].baseUrl], ORDERDETAIL_GETORDERDETAILCODE) withParameter:@{@"mainOrderCode": parentDic[@"code"],@"token":[UserDefaultUtil valueForKey:USER_TOKEN],} withVC:self netName:@"扫码卸货-获取运单code" success:^(id response, NSString *msg) {
                        
                        QRZhuangHuoViewController *qrzhvc = [[QRZhuangHuoViewController alloc] init];
                        qrzhvc.ydModel = [YunDanCenterModel mj_objectWithKeyValues:parentDic];
                        qrzhvc.startCountrySubdivisionCode = response[@"shipperSubdivisionCode"];
                        qrzhvc.endCountrySubdivisionCode = response[@"consigneeSubdivisionCode"];
                        qrzhvc.coalUnit = response[@"coalUnit"];
                        qrzhvc.code = response[@"orderDetailCode"];
                        qrzhvc.orderCode = response[@"code"];
                        qrzhvc.branchCode = parentDic[@"branchCode"];
                        qrzhvc.shippingNoteNumber = response[@"shippingNoteNumber"];///卸货时，这个接口直接返回这个字段
                        qrzhvc.status = 1;///卸货
                        [weakSelf.navigationController pushViewController:qrzhvc animated:YES];
                        
                    } failure:^(NSInteger code, NSString *msg) {
                        
                        [DCSpeedy dc_SetUpSingleAlterWithView:self Title:@"温馨提示" Message:msg tureTitle:@"确定" Sure:^{
                            [weakSelf.navigationController popViewControllerAnimated:YES];
                        }];
                        
                    }];
                }
                
            } failure:^(NSInteger code, NSString *msg) {
                
            }];
            
        }
        
    } else {
        
        NSString *message = CJStringWithFormat(@"确定要绑定该车辆吗？");
        
        [DCSpeedy dc_SetUpAlterWithView:self Title:@"操作提醒" Message:message Sure:^{
            
            NSDictionary *branch = [UserDefaultUtil valueForKey:Login_Branch];
            
            NSDictionary *parmas = @{
                @"vehicleCode": dic[@"code"],
                @"driverCode": branch[@"code"],
                @"token":[UserDefaultUtil valueForKey:USER_TOKEN],
            };
            [HTTPManager postNetworkRequest:CJStringWithFormat(@"%@%@", [NSString stringWithFormat:@"%@/ntocc-basic-api",[ReAddressDynamic shared].baseUrl], DRIVER_BINDVEHICLEBYQRCODE) withParameter:parmas withVC:self netName:@"扫码绑车" success:^(id response, NSString *msg) {
                
                [XSInfoView showInfo:msg onView:weakSelf.view];
                
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 1.5 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void){
                    [weakSelf.navigationController popViewControllerAnimated:YES];
                });
                
            } failure:^(NSInteger code, NSString *msg) {
                
            }];
            
        } Cancel:^{
            
            [weakSelf.navigationController popViewControllerAnimated:YES];
            
        }];
    }
}

/// 选择承运车辆
/// @param block 回调
/// @param isShow 是否显示车辆选框
- (void)getVehicleCode:(VehileCodeBlock)block isShow:(BOOL)isShow {
    NSDictionary *pamars = @{
        @"authStatusExt": @3,
        @"pageSize": @"9999",
        @"pageNum": @1,
    };
    
    NSString *listUrl = CJStringWithFormat(@"%@%@", [NSString stringWithFormat:@"%@/ntocc-basic-api",[ReAddressDynamic shared].baseUrl], @"/vehicle/bindList");
    
    @weakify(self);
    [HTTPManager jsonNetworkRequestWithMethod:@"GET"
                                    urlString:listUrl
                                withParameter:pamars
                                       withVC:self
                                      netName:@"车辆列表"
                                      success:^(id response, NSString *msg) {
        @strongify(self);
        NSArray *vehicleArr = [DriverVehicleModel mj_objectArrayWithKeyValuesArray:response[@"records"]];
        
        if (isShow) {
            NSMutableArray *arr = [NSMutableArray array];
            for (DriverVehicleModel *model in vehicleArr) {
                [arr addObject:model.licenseNumber];
            }
            
            BRStringPickerView *stringPickerView = [[BRStringPickerView alloc] initWithPickerMode:BRStringPickerComponentSingle];
            stringPickerView.title = @"选择承运车辆";
            stringPickerView.dataSourceArr = arr;
            stringPickerView.resultModelBlock = ^(BRResultModel *resultModel) {
                DriverVehicleModel *vehicle = vehicleArr[resultModel.index];
                NSString *vehicleCode = vehicle.code;
                if (block) {
                    block(vehicleCode, vehicleArr);
                }
            };
            
            BRPickerStyle *customStyle = [BRPickerStyle pickerStyleWithThemeColor:Theme_ColorValue];
            customStyle.topCornerRadius = 7;
            stringPickerView.pickerStyle = customStyle;
            [stringPickerView show];
            
        } else {
            if (block) {
                block(@"", vehicleArr);
            }
        }
        
    } failure:^(NSInteger code, NSString *msg) {
        
    }];
}


#pragma mark -底部功能项
//打开相册
- (void)openPhoto
{
    __weak __typeof(self) weakSelf = self;
    [LBXPermission authorizeWithType:LBXPermissionType_Photos completion:^(BOOL granted, BOOL firstTime) {
        if (granted) {
            [weakSelf openLocalPhoto:NO];
        }
        else if (!firstTime )
        {
            [LBXPermissionSetting showAlertToDislayPrivacySettingWithTitle:@"提示" msg:@"没有相册权限，是否前往设置" cancel:@"取消" setting:@"设置"];
        }
    }];
}

//开关闪光灯
- (void)openOrCloseFlash
{
    [super openOrCloseFlash];
    
    if (self.isOpenFlash)
    {
        [_btnFlash setImage:[UIImage imageNamed:@"CodeScan.bundle/qrcode_scan_btn_flash_down"] forState:UIControlStateNormal];
    }
    else
        [_btnFlash setImage:[UIImage imageNamed:@"CodeScan.bundle/qrcode_scan_btn_flash_nor"] forState:UIControlStateNormal];
}

@end
